<template>
    <div>

        <selectArea
        :homeInfo="homeId"
        homeType="split"
        :hasDevice="hasDevice"
        @on-delete-home="handleDeleteHome"
        @on-edit-info="ok"
        @on-change="handleAreaChange"></selectArea>

        <Card class="no-border-card" style="margin-top:24px;">
            <p slot="title">
                房间信息

                <Button type="primary"
                class="select-top-btn btn-in-top-large"
                v-if="homeId"
                @click="openRoomModal">
                新增房间
                </Button>
            </p>

            <Row
                :gutter="16"
                v-if="!homeId"
                class="range"
                type="flex"
                justify="space-between">
                <InputNumber v-model="number" placeholder="房间数量" style="width:200px;margin-right:6px;margin-left:7px;" :min="1" :max="20"></InputNumber>
                <i-col>
                    <Button type="primary" @click="addHouse()" style="margin-right:6px;">生成房间</Button>
                    <Button type="primary" @click="delHouse()">清空房间</Button>
                </i-col>
            </Row>

            <div class="r-split-wrap">
                <div class="r-split-container">
                    <div
                        class="r-split-item"
                        v-for="(room,index) in rooms"
                        :key="index">
                        <div class="r-split-item-main">
                            <div class="f-room-box">
                                <i-input
                                    v-if="!homeId"
                                    v-model="rooms[index]"
                                    class="f-room-content">
                                </i-input>

                                <i-input
                                    v-if="homeId"
                                    @on-change="editVisibleMap[index]=true"
                                    :readonly="!room.editable" :ref="room.id"
                                    v-model="rooms[index]['room_name']"
                                    class="f-room-content">
                                </i-input>
                                <span class="f-room-append" @click="delTag(index,room)">
                                    <Icon class="del-room-icon" type="ios-close-empty" ></Icon>
                                </span>
                            </div>
                        </div>
                        <div class="r-split-item-extra">
                            <Button type="ghost" class="is-hide-btn" v-if="homeId && !room.toBeSave" @click="setRoomChange(room)">修改</Button>
                            <Button type="ghost" v-if="homeId && room.toBeSave" @click="editRoomName(room,index)">保存</Button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- <Row v-if="!homeId">
                <Col offset="11">
                    <Button type="primary" @click="ok()">保存</Button>
                </Col>
            </Row> -->
        </Card>

        <Modal v-model="isAddRoomVisible " title="新增房间">
            <Form ref="addRoomForm" :model="formItem" :label-width="80" :show-message="false">
                <FormItem label="房间名称" prop="roomName">
                    <Input v-model="formItem.roomName" placeholder="房间名称"/>
                </FormItem>
                <!-- <FormItem label="房间楼层" prop="roomFloor">
                    <Input v-model="formItem.roomFloor" :maxlength="11" placeholder="房间楼层"></Input>
                </FormItem> -->
                <div style="padding-left:80px;font-size:12px;">若房源用电公摊设置为按比例分摊，新增房间需设置分摊比例。</div>
            </Form>

            <div slot="footer">
                <Button type="text" size="large" @click="cancelAddRoom">取消</Button>
                <Button type="primary" size="large" @click="addRoom">确定</Button>
            </div>
        </Modal>

    </div>
</template>
<script>
import countBy from 'lodash/countBy'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
// import dataCenter from '@/libs/dataCenter';
import selectArea from '../selectArea'
let editVisibleMap = new Array(1000)
export default {
  props: {
    homeId: ''
  },
  data () {
    return {
      hasDevice: false,
      isLoading: false,
      areaInfo: '',
      number: null,
      rooms: [],

      isAddRoomVisible: false,
      formItem: {
        roomName: ''
      },
      editVisibleMap: util.deepNormalCopy(editVisibleMap)
    }
  },

  components: {
    selectArea
  },

  mounted () {
    if (this.homeId) {
      this.getRooms(this.homeId.id)
    }
  },
  methods: {
    /**
        * 新增房间
        */
    openRoomModal () {
      const { length } = this.rooms
      if (length >= 20) {
        this.$Message.error('分散式房源最多只能新建20个房间')
        return
      }
      this.isAddRoomVisible = true
    },
    handleAreaChange (areaInfo) {
      this.areaInfo = areaInfo
    },
    addHouse () {
      if (!this.number) {
        this.$Message.error('请选择要生成的房间数量')
        return
      }
      this.number = parseInt(this.number)
      // this.rooms = Array.apply(null, new Array(Number(this.number))).map((v, i) => {
      //     return i + 1
      // })
      this.rooms = new Array(this.number).fill(0).map((item, index) => {
        const str = '000' + (index + 1)
        return str.slice(-4)
      })
    },
    setRoomChange (val) {
      this.rooms.forEach(room => {
        // this.$set(room, 'room_name', room.name)
        this.$set(room, 'toBeSave', false)
      })
      this.$set(val, 'toBeSave', true)
      this.$set(val, 'editable', true)
      this.$refs[val.id][0].focus()
    },
    editRoomName (v, index) {
      const name = v.room_name.trim()
      if (!/^[\w\u4e00-\u9fa5-]{1,30}$/g.test(name)) {
        this.$Message.info('请使用30位以内的中英文/数字/-连接的组合')
        return
      }
      this.updateRoom(v, { room_name: v.room_name })
      this.$set(this.editVisibleMap, index, false)
    },
    delHouse () {
      this.rooms = []
    },
    addTag () {
      this.tags.push(null)
    },
    delTag (index, item) {
      if (this.isLoading) {
        this.$Message.info('操作中，请稍后..')
        return
      }

      if (this.homeId) {
        this.$Modal.confirm({
          title: '确定删除?',
          content: util.escapeHtml(`房间 ${item.name} 将会被删除`),
          onOk: () => {
            this.deleteRoom(item.id, index)
          }
        })
      } else {
        this.rooms.splice(index, 1)
      }
    },
    ok (lease_type) {
      if (this.homeId) {
        this.addHomes(lease_type, this.homeId.id)
      } else {
        this.addHomes(lease_type)
      }
    },
    // 删除房间
    deleteRoom (id, index) {
      const msg = this.$Message.loading({ content: '提交中...' })
      this.isLoading = true
      http.request(this, api.room_del, [id], null, (res, err) => {
        msg()
        if (err || !res) {
          this.isLoading = false
          return
        }
        this.rooms.splice(index, 1)
        this.$Message.success('删除成功')
        this.isLoading = false
      })
    },

    // 新增单个房间
    addRoom () {
      let name = this.formItem.roomName.trim()
      let homeId = this.homeId.id
      if (!/^[\w\u4e00-\u9fa5-]{1,30}$/g.test(name)) {
        this.$Message.info({
          content: '请使用30位以内的中英文/数字/-连接的组合',
          duration: 3
        })
        return false
      } else if (this.rooms.some(r => r.room_name === name)) {
        this.$Message.info({
          content: '该房间名已存在',
          duration: 2
        })
        return false
      }

      let params = { rooms: [{ name }] }

      util.log(homeId, params)

      http.request(this, api.room_create, [homeId], params, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('新增房间成功')
        this.getRooms(homeId)

        this.formItem.roomName = ''
        this.isAddRoomVisible = false
      })
    },
    cancelAddRoom () {
      this.formItem.roomName = ''
      this.isAddRoomVisible = false
    },

    // 获取房源下的房间
    getRooms (id) {
      this.editVisibleMap = util.deepNormalCopy(editVisibleMap)

      http.request(this, api.room_list, [id], { with_device: 1 }, (res, err) => {
        if (err || !res) {
          return
        }
        res.forEach(room => {
          if (room.devices.length) this.hasDevice = true
        })
        this.rooms = res
          .filter(item => {
            item.name = item.room_name
            return item.room_type === 1
          })
          .sort((a, b) => {
            return a.room_name - b.room_name || b.room_type - a.room_type || a.room_name.localeCompare(b.room_name)
          })
      })
    },

    // 更新房间
    updateRoom (room, data) {
      if (data.room_name === '公区') {
        this.$Message.info('房间名不能为公区')
        return
      }
      if (data.room_name === '') {
        this.$Message.info('房间名不能为空')
        return
      }
      const msg = this.$Message.loading({ content: '提交中...' })
      http.request(this, api.room_update, [room.id], data, (res, err) => {
        msg()
        if (err || !res) {
          return
        }
        room.toBeSave = false
        this.$Message.success('修改成功')
      })
    },

    checkRoomNames () {
      let result = ''
      this.rooms.forEach(room => {
        if (room === '') result = '房间名不能为空'
        if (room === '公区') result = '房间名不能为公区'
      })
      return result
    },
    checkRooms () {
      if (this.rooms.length === 0) {
        this.$Message.info('请创建房间')
        return false
      }
      /** 统计名字重复的房间数量 */
      const roomsCount = countBy(this.rooms)
      const [ duplicateRoomNames, illegalNames ] = Object.keys(roomsCount).reduce(([ wrongNames, illegalNames ], roomName) => {
        if (roomsCount[roomName] > 1) wrongNames.push(roomName)
        if (!/^[\w\u4e00-\u9fa5-]{1,15}$/g.test(roomName)) illegalNames.push(roomName)
        return [ wrongNames, illegalNames ]
      }, [ [], [] ])

      if (duplicateRoomNames.length || illegalNames.length) {
        this.$Modal.confirm({
          render: h => (
            <div>
              <div class='margin-bottom-20'><strong>创建失败</strong></div>
              { duplicateRoomNames.length > 0 && <div class='margin-bottom-10'>以下房间名重复</div> }
              {
                duplicateRoomNames.map((detail, index) => <div class='margin-bottom-10' key={index}>{detail}</div>)
              }
              { illegalNames.length > 0 && <div class='margin-bottom-10'>以下房间名请使用15位以内的中英文/数字/-连接的组合</div> }
              {
                illegalNames.map((detail, index) => <div key={index}>{detail}</div>)
              }
            </div>
          )
        })
        return false
      }
      return true
    },
    // 添加房源
    addHomes (lease_type, id) {
      if (this.isLoading) {
        this.$Message.info('操作中，请稍后..')
        return
      }
      // 新增检查全部房间
      if (!this.homeId && !this.checkRooms()) return
      const checkRoomNamesResult = this.checkRoomNames()
      if (!id && checkRoomNamesResult) {
        this.$Message.info(checkRoomNamesResult)
        return
      }

      let areaInfo = this.areaInfo

      if (JSON.stringify(this.rooms) === '[]' && !this.homeId) {
        this.$Message.error('请创建房间')
        return
      }

      let obj = {
        home_name: areaInfo.home_name,
        home_type: 1,
        street: areaInfo.street,
        block: areaInfo.block,
        district: areaInfo.area,
        city: areaInfo.city,
        province: areaInfo.province,
        country: '中国',
        number: areaInfo.doorNumber ? areaInfo.doorNumber : null,
        description: areaInfo.home_name
      }
      obj.branch_id = areaInfo.branch_id ? areaInfo.branch_id : 0

      util.log('params', obj)
      // return;

      this.isLoading = true
      const submiting = this.$Message.loading({
        content: '提交中...',
        duration: 0
      })

      if (id) {
        http.request(this, api.home_update, [id], obj, (res, err) => {
          this.isLoading = false
          submiting()
          if (err || !res) {
            return
          }
          this.$emit('update', id, true)
          this.$Message.success('修改成功')
        })
      } else {
        obj.lease_type = lease_type
        http.request(this, api.home_create, null, obj, (res, err) => {
          this.isLoading = false

          if (err || !res) {
            submiting()
            return
          }
          let home_id = res.home_id
          let homes = this.rooms.map(item => {
            return { name: item.toString() }
          })
          let obj = {
            rooms: homes
          }
          this.addRooms(home_id, obj, submiting)
        })
      }
    },
    // 添加房间
    addRooms (home_id, homes, submiting) {
      this.isLoading = true
      http.request(this, api.room_create, [home_id], homes, (res, err) => {
        this.isLoading = false
        submiting()
        if (err || !res) {
          return
        }
        this.$Message.success('创建成功')
        this.$emit('update', 'split')
      })
    },
    handleDeleteHome (homeId) {
      this.$emit('update', homeId)
    }
  }
}
</script>

<style lang="less">
.topBar {
    color: #1c2438;
    font-size: 18px;
    line-height: 50px;
    width: 100%;
    height: 50px;
    background: #efeff1;
    border-left: 5px solid #05bac5;
}
.range {
    margin-bottom: 20px;
}
.bg {
    background: #efeff1;
    margin-bottom: 20px;
    padding-top: 20px;
    padding-bottom: 20px;
}

.del-room-icon {
    font-size: 24px;
}
.room-item:hover {
    .room-operate-btn {
        display: block;
    }
    .ivu-input-group-append {
        cursor: pointer;
        color: #fff;
        background-color: #05bac5;
    }
}
.r-split-item{
    flex: 0 1 25%
}
.r-split-wrap {
    background-color: #fff;
    border-top: 1px solid #e9eaec;
    border-bottom: 1px solid #e9eaec;
    border-right: 1px solid #e9eaec;
}
.ivu-form-item {
    margin-bottom: 10px;
}
</style>
